<template>
  <div class="login">
    <el-form
      :model="form"
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="demo-form"
      label-position="top"
    >
      <el-form-item label="用户账号" prop="phone">
        <el-input placeholder="请输入用户账号" v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          placeholder="请输入密码"
          type="password"
          v-model="form.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :loading="isLoading"
          @click="submitForm('loginForm')"
          >立即登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/service/user.js'
export default {
  name: 'login',
  data () {
    return {
      // 加载状态
      isLoading: false,
      form: {
        phone: '18201288771',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度为 6 到 18 位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async submitForm (formName) {
      // 使用同步函数方式验证表单，需要使用try..catch捕获错误
      try {
        const result = await this.$refs[formName].validate()
        // console.log(result)
        if (result) {
          // console.dir(login)
          this.isLoading = true
          const { data } = await login(this.form)
          // console.log(data)
          if (data.success) {
            this.$message.success('登录成功')
            this.isLoading = false
            // 将获取到的用户信息存储到vuex
            this.$store.commit('setUser', data.content)
            // 跳转可能存储的redirect路由路径
            this.$router.push(this.$route.query.redirect ?? '/')
          } else {
            this.$message.error('登录失败')
          }
        }
      } catch (error) {
        console.log('检验失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  .demo-form {
    width: 400px;
    // height: 500px;
    padding: 30px 40px;
    text-align: left;
    border-radius: 8px;
    background-color: #fff;
    box-sizing: border-box;
    .el-button {
      width: 100%;
      margin-top: 60px;
    }
  }
}
</style>
